<template>
  <div style="padding-top:5px;height:950px; box-sizing:border-box;" >
    <div :style="searchDiv.styles.width">
      <el-form :inline="true" :model="fcapNoContent" class="demo-form-inline">

        <el-form-item label="内容" style="margin-bottom:10px;">
            <el-input v-model="fcapNoContent.content" placeholder="根据内容搜索" style="width:650px;"></el-input>
        </el-form-item>
        <el-form-item style="margin-bottom:10px;">
          <el-button type="primary" @click="submitQuery" >查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="margin:0 auto;width:315px;text-align:left; margin-bottom:8px;">
        <el-button type="primary" @click="handleAdd" style="" size="small">添加数据</el-button>
        <el-button @click="dialogUploadVisible = true" type="primary" size="small" style="margin-left: 16px;">excel批量添加数据</el-button>
    </div>
    <el-table
      :data="tableData"
      border
      stripe
      size="mini"
      :style="tableStyle.tableHead">   
      <el-table-column
        prop="no"
        label="no"
        :width="tableStyle.no.width">
      </el-table-column>
      <el-table-column
        prop="content"
        label="内容"
        >
        <template slot-scope="scope">
          <span  v-html="showDate(scope.row.content)"></span>
        </template>
      </el-table-column> 
      <el-table-column label="操作" :width="tableStyle.operator.width">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>        
          <el-button slot="reference"
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="pageSizeArr"
      :page-size="pageSize"
      :layout="layout"
      :pager-count="pagerCount"
      :total="totalRecord">
    </el-pagination>
    <div v-if="totalVisible" style="font-size:14px;padding-top:10px">共{{totalRecord}} 条</div>
    <el-dialog :title="dialogFormTitle" :visible.sync="dialogFormVisible" :width="dialogWidth" :close-on-click-modal="closeOnClickMdal">
      <el-form :model="form" :label-width="formWidth" :rules="rules" ref="form">
        <el-form-item label="组号" :label-width="formLabelWidth" prop="no">
          <el-input v-model="form.no" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="内容" :label-width="formLabelWidth" prop="content">
          <el-input v-model="form.content" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSave('form')">取 消</el-button>
        <el-button type="primary" v-preventReClick="3500"  @click="submitInsertOrUpdate('form')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="excel批量添加数据" :visible.sync="dialogUploadVisible" :width="dialogWidth" :close-on-click-modal="closeOnClickMdal">
      <div style="padding-bottom:20px;"><a href="javascript:void(0);" v-preventReClick="5000" @click="downExcel">excel模板下载</a></div>
      <el-upload
        class="upload-demo"
        ref="upload"
        accept="xls"
        :limit="fileListLimit"
        action="/api/blog/upload"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :file-list="fileList"
        :on-exceed="handleExceed"
        :before-upload="beforeUpload"
        :on-success="uploadSuccess"
        :auto-upload ="false">
        <el-button slot="trigger" size="small" type="primary" v-show="selectFileVisible">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传并保存数据</el-button>
        <div slot="tip" class="el-upload__tip">只能上传.xls和xlsx文件，且不超过10M</div>
      </el-upload>
    </el-dialog>

  </div>
</template>

<script>
import { mapState } from "vuex";
import API from '@/api/blogs.js'
  export default {
    name: 'FcapNoContent',
    data() {
      return {
        // 分页组件配置
        currentPage: 1,
        totalRecord:0,
        pageSize:10,
        pageSizeArr:[10,15,20, 30, 50],
        layout:"total, sizes, prev, pager, next, jumper",
        pagerCount:7,
        totalVisible:false,
        // 分页查询
        fcapNoContent: {
          content: '',
          pageNo:1,
          pageSize:10
        },
        // 搜索框配置
        searchDiv:{
          styles:{
              width: '100%'
          }
        },
        // 对话框设置
        closeOnClickMdal:false,
        formLabelWidth: 'auto',
        dialogWidth:'50%',
        formWidth:'100%',
        dialogFormVisible: false,
        dialogUploadVisible:false,
        dialogFormTitle: '',
        delPopVisible: false,
        // 表单提交
        form: {
          id: null,
          no: '',
          content: ''
        },
        rules:{
          content: [
            { required: true, message: '请输入内容', trigger: 'blur' }  
          ],
          no:[
            { required: true,  message: '请输入组号', trigger: 'blur' } 
          ]
        },
        // 表格数据
        tableData: [{    
          no: '',
          content: ''
        }],
        tableStyle:{
          no:{
            width:'100px'
          },
          operator:{
            width:'150px'
          },
          tableHead:{
            'margin': '0 auto',
            'width':'50%'
          }
        },
        // 文件上传
        fileList: [
         
        ] ,
        fileListLimit:1,
        selectFileVisible:true,
      }
    },
    created(){
      this.isMobile();
      this.selectByContentPage();
    },
    computed: {//加载数据过程loading
	    ...mapState(["isLoading"])
	  },
    methods: {
      downExcel() {
        this.dialogUploadVisible = false;
        API.downloadTemplate().then(data => {
            console.log(data)

          /** 获取生成设置好的文件名 */
            var filename = data.headers["content-disposition"];
            
            filename = filename.split("=")[1];
            filename = decodeURIComponent(filename, "utf-8");
            /** 接收文件流 */
            const blob = new Blob([data.data]);
            let url = URL.createObjectURL(blob);
            /** 模拟浏览器操作Document，并模拟下载动作 */
            let link = document.createElement("a");
            link.style.display = "none";
            link.href = url;
            link.setAttribute("download", filename);
            document.body.appendChild(link);
            link.click();
          }, 
          error => {
            console.log(error);
            this.$message.error("下载异常，请稍后再试");
          });
      },
      isMobile() {
        this.flag = navigator.userAgent.match(
            /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
        );
        console.log(this.flag);
        if(this.flag === null) {
            console.log("pc端");
            this.rightNavShow = true;            
        }else {
            console.log("移动端");
            this.rightNavShow = false;
            this.dialogWidth = '80%';
            this.searchDiv.styles.width='100%';
            this.pageSizeArr = [10];
            this.layout = "prev, pager,next, jumper";
            this.pagerCount = 3;
            this.totalVisible = true;
            this.tableStyle.tableHead={
              'margin':'0 auto',
              'width':'100%'
            }
            this.tableStyle.no.width='50px'
            this.tableStyle.operator.width='148px'
        }
      },

       handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.fcapNoContent.pageSize  = val;
        this.fcapNoContent.pageNo  = 1;
        this.selectByContentPage();
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.fcapNoContent.pageNo  = val;
        this.selectByContentPage();
      },
      submitQuery(){
        this.fcapNoContent.pageNo = 1;
        this.selectByContentPage();
      },

      // 列表查询
      selectByContentPage:function(){
        console.log("selectByContentPage...")
        console.log(this.fcapNoContent.content);
        API.selectByContentPage(this.fcapNoContent).then(res => {
          //请求成功
          //console.log("queryBlogList:"+ JSON.stringify(res));
          if(res.code == '00000000'){
            console.log(res.data)
            this.tableData = res.data.list;
            this.currentPage = res.data.pageNo;
            this.totalRecord =  res.data.count;
            this.pageSize = res.data.pageSize;
            
          }
        }).catch(err => {
            //请求失败
            console.log("error:"+ err)
        })
      },
      // 数据标红
      showDate(val) {
        val = val + "";
        let flag = true;
        if(this.fcapNoContent.content !== ""){
          let arr = this.fcapNoContent.content.split("."); 
          for(var i = 0; i< arr.length; i++){
              if(val.indexOf(arr[i]) == -1){
                return val;
              }
          }
          for(var i = 0; i< arr.length; i++){
            val = val.replace("."+arr[i], '.<font color="red">' + arr[i] + "</font>");
            val = val.replace(arr[i]+".", '<font color="red">' + arr[i] + "</font>.");
          }
          return val;
        }else {
          return val;
        }
      },
      submitInsertOrUpdate(formName){
        console.log("新增提交submitInsertOrUpdate");
        console.log(this.form);
        let flag = false;
        this.$refs[formName].validate((valid) => {
          if (valid) {
          } else {
            console.log('error submit!!');
            flag = true;
            return false;
          }
        });
        if(flag){
          return;
        }
       let _self = this
        API.insertOrUpdateFcapNoContent(this.form).then(res => {
          _self.$refs[formName].resetFields();
          //请求成功
          //console.log("queryBlogList:"+ JSON.stringify(res));
          if(res.code == '00000000'){
            if(!this.form.id){
              this.$message({
                type: 'success',
                message: '添加成功!'
              });
            }else{
              this.$message({
                type: 'success',
                message: '修改成功!'
              });
            }
            _self.dialogFormVisible = false;
            //_self.form = {"id":"","no":"", "content":""};
            _self.selectByContentPage();
          }
          

        }).catch(err => {
            //请求失败
            console.log("error:"+ err)
        })
      },
      cancelSave(formName){
        this.$refs[formName].resetFields();
        this.dialogFormVisible = false;
      },
      
      handleAdd() {
        console.log("新增");
        this.dialogFormTitle = '新增数据';
        this.dialogFormVisible = true;
        this.form = {"id":"","no":"", "content":""};
      },
      handleEdit(index, row) {
        console.log("修改", index, row);
        this.dialogFormTitle = '修改数据';
        this.dialogFormVisible = true;
        Object.assign(this.form, row);
        console.log("修改:", this.form)

      },
      handleDelete(index, row) {
        console.log("delete:", index, row);
        let _self = this;
        this.$confirm('此操作将永久删除'+row.content+', 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center:true
        }).then(() => {
          API.deleteFcapNoContent({"id": row.id}).then(res => {
            //请求成功
            //console.log("queryBlogList:"+ JSON.stringify(res));
            if(res.code == '00000000'){
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              _self.selectByContentPage();
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      submitUpload() {
        this.$refs.upload.submit();
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
        this.selectFileVisible = true;
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeUpload(file) {
          console.log(file)
          var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)
          const extension = testmsg === 'xls'
          const extension2 = testmsg === 'xlsx'
          const isLt2M = file.size / 1024 / 1024 < 10
          if(!extension && !extension2) {
              this.$message({
                  message: '上传文件只能是 xls、xlsx格式!',
                  type: 'warning'
              });
          }
          if(!isLt2M) {
              this.$message({
                  message: '上传文件大小不能超过 10MB!',
                  type: 'warning'
              });
          }
        return (extension || extension2) && isLt2M
      },
      uploadSuccess(response, file, fileLis){
          console.log("upload response")
          console.log(response)
          this.dialogUploadVisible=false
          this.fileList=[]
          if(!!response && response.code =='00000000'){
            this.$message({
                  message: '数据添加成功',
                  type: 'success'
            });
            this.selectByContentPage();
          }else{
            this.$message({
                  message: '上传失败，请稍后重试',
                  type: 'error'
            });
          }
      }
    }
  }
</script>
<style scoped>
.demo-form-inline{
  margin:0 auto;
}
.el-form-item:first{
  margin-left:0px;
}

input{
  width:100px !important;
}
</style>